package com.woniuxy.thred.others;

/**
 * description: LockTest <br>
 * date: 2022/2/6 7:38 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 不可重入锁：锁不可以延续使用
 */
public class LockTest02 {
    Lock lock = new Lock();

    public void a() throws InterruptedException {
        lock.lock();
        doSomething();
        lock.unlock();
    }

    //不可重入
    public void doSomething() throws InterruptedException {
        lock.lock();
        //
        lock.unlock();
    }

    public static void main(String[] args) throws InterruptedException {
        LockTest02 lockTest02 = new LockTest02();
        lockTest02.a();
        lockTest02.doSomething();
    }
}

//不可重入锁
class Lock {
    //是否占用
    private boolean isLocked = false;

    //使用锁
    public synchronized void lock() throws InterruptedException {
        while (isLocked) {
            wait();
        }
        isLocked = true;
    }

    //释放锁
    public synchronized void unlock() {
        isLocked = false;
        notify();
    }
}